<?php
namespace app\admin\controller\order;

use app\admin\model\Order;
use app\admin\model\Product;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Index extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];
    protected $searchFields = ['order_sn'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Order();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //搜索查询处理
//            $filter = $this->request->get("filter", '');
//            $op = $this->request->get("op", '', 'trim');
//            if (!empty($filter) && !empty($op)) {
//                $filter = (array)json_decode($filter, true);
//                $op = (array)json_decode($op, true);
//                unset($filter['customer_id']);
//                unset($op['customer_id']);
//                $this->request['filter'] = json_encode($filter);
//            }


            // 搜索查询处理
            $mimetypeQuery = [];
            $op = $this->request->get("op", '', 'trim');
            $op = (array)json_decode($op, true);
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['customer_name'])) {
                $customer_id = Db::name('customer')->where('name','like',"%{$filterArr['customer_name']}%")->value('id');
                $filterArr['customer_id'] = !empty($customer_id) ? $customer_id : -1;
                $op['customer_id'] = '=';
                unset($filterArr['customer_name']);
                unset($op['customer_name']);
                $this->request->get(['op' => json_encode($op)]);
            }



            $this->request->get(['filter' => json_encode($filterArr)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $whereNew = [
                'is_delete' => 0
            ];
            $list = $this->model
                ->where($mimetypeQuery)
                ->where($where)
                ->where($whereNew)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function ($item, $key) {
                   $item['customer_name'] = Db::name('customer')->where(['id' => $item['customer_id']])->value('name');
                });

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            $subData['row']['admin_id'] = $this->auth->id;
            $subData['row']['order_sn'] = generate_unique_order_sn();

            try {
                Db::startTrans();
                $this->model->allowField(true)->save($subData['row']);

                //添加订单详情
                $productCol = Db::name('product')->where(['is_delete' => 0])->column('name,spec','id');
                $orderDetails = json_decode($subData['row']['test'],true);
                foreach ($orderDetails as $detail) {
                    $orderDetailsData[] = [
                        'order_id' => $this->model->id,
                        'product_id' => $detail['product_id'],
                        'product_name' => $productCol[$detail['product_id']]['name'],
                        'product_spec' => $productCol[$detail['product_id']]['spec'],
                        'product_standard' => $detail['product_standard'],
                        'product_material' => $detail['product_material'],
                        'source' => $detail['source'],
                        'remark' => $detail['remark'],
                        'number' => $detail['number'],
                        'price'  => $detail['price'],
                        'amount' => number_format($detail['number'] * $detail['price'],2),
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }
                Db::name('order_goods')->insertAll($orderDetailsData ?? []);
            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success(' 提交成功');
        }

        // 客户列表
        $customerLists = Db::name('customer')->where(['status' => 1,'is_delete' => 0])->field('id,name')->column('name','id');
        $this->assign('customerLists', $customerLists);

        return $this->view->fetch();
    }

    public function edit($ids = "")
    {
        if ($this->request->isAjax()) {
            $subData = $this->request->param();

            try {
                $model = $this->model->find($ids);
                $model->allowField(true)->save($subData['row']);

                Db::name('order_goods')->where(['order_id' => $ids])->delete();
                //添加订单详情
                $productCol = Db::name('product')->where(['is_delete' => 0])->column('name,spec','id');
                $orderDetails = json_decode($subData['row']['test'],true);
                foreach ($orderDetails as $detail) {
                    $orderDetailsData[] = [
                        'order_id' => $model->id,
                        'product_id' => $detail['product_id'],
                        'product_name' => $productCol[$detail['product_id']]['name'] ?? '',
                        'product_spec' => $productCol[$detail['product_id']]['spec'] ?? '',
                        'product_standard' => $detail['product_standard'],
                        'product_material' => $detail['product_material'],
                        'source' => $detail['source'],
                        'remark' => $detail['remark'],
                        'number' => $detail['number'],
                        'price'  => $detail['price'],
                        'amount' => number_format($detail['number'] * $detail['price'],2),
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }
                Db::name('order_goods')->insertAll($orderDetailsData ?? []);
            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success('修改成功');
        }

        $detail = $this->model->find($ids);
        $detailLists = Db::name('order_goods')->where(['order_id' => $detail['id']])->select();
        $detail['detail_json'] = json_encode($detailLists,256);
        $this->assign('detail', $detail);

        // 客户列表
        $customerLists = Db::name('customer')->where(['status' => 1,'is_delete' => 0])->field('id,name')->column('name','id');
        $this->assign('customerLists', $customerLists);

        return $this->view->fetch();
    }


    // 详情
    public function detail($ids = '')
    {
        $detail = $this->model->find($ids);
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $detailLists = Db::name('order_goods')->where(['order_id' => $detail['id']])->select();
        $detail['details'] = $detailLists;
        $detail['total_amount'] = array_sum(array_column($detail['details'],'amount'));

        $this->assign('order', $detail);

        return $this->view->fetch();
    }

    // 打印
    public function print(){
        $ids = $this->request->get('id');
        $ids = explode(',',$ids);
        $lists = $this->model->where('id','in',$ids)->select();
        $sum_amount = 0;
        foreach ($lists as &$value){
            $goods_info = Db::name('order_goods')->where('order_id',$value['id'])->select();
            $sum_amount += array_sum(array_column($goods_info,'amount'));
            $value['goods_info'] = $goods_info;

            $value['sum_amount'] = $sum_amount;
        }
        $this->assign('lists',$lists);
        return $this->fetch();
    }
}
